package com.doyens.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doyens.reggie.commons.R;
import com.doyens.reggie.domain.Category;
import com.doyens.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    // 根据type查询分类
    @GetMapping("list")
    public R<List<Category>> list(@RequestParam(name = "type",required = false) Integer type){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type != null,Category::getType,type);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

    // 修改分类
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){
        categoryService.updateById(category);// 公共字段填充
        return R.success("修改成功");
    }

    // 删除分类
    @DeleteMapping
    public R<String> deleteCategory(Long id){
        categoryService.mydeleteCategory(id);//直接调用service的删除
        return R.success("删除成功");
    }
    // 分页查询
    @GetMapping("/page")
    public R<IPage> page(int page,int pageSize){
        Page<Category> params = new Page<>(page, pageSize);
        Page<Category> pb = categoryService.page(params,new LambdaQueryWrapper<Category>().orderByAsc(Category::getType));
        return R.success(pb);
    }

    // 添加
    @PostMapping
    public R<String> saveCategory(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }
}
